package com.ysd.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.ysd.entity.Img;
import com.ysd.util.DBManager;

public class ImgDaoImpl {
	public 	List<Img> getImg() {
		List<Img> imgList = new ArrayList<Img>();
		
		Connection conn = DBManager.getConnection();
		Statement st = null;
		ResultSet rs = null;
		
		try {
			st = conn.createStatement();
			rs = st.executeQuery("select * from img");
			while(rs.next()) {
				int imgId = rs.getInt("imgId");
				String imgPath = rs.getString("imgPath");
				Img img = new Img(imgId, imgPath);
				imgList.add(img);
			}
			return imgList;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}finally {
			DBManager.closeAll(conn, st, rs);
		}
	}
	
	public 	List<Img> getImgPage(int page ,int size) {
		List<Img> imgList = new ArrayList<Img>();
		
		Connection conn = DBManager.getConnection();
		Statement st = null;
		ResultSet rs = null;
		
		try {
			st = conn.createStatement();
			rs = st.executeQuery("SELECT * from img limit "+(page-1)*size+","+size);
			while(rs.next()) {
				int imgId = rs.getInt("imgId");
				String imgPath = rs.getString("imgPath");
				Img img = new Img(imgId, imgPath);
				imgList.add(img);
			}
			return imgList;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}finally {
			DBManager.closeAll(conn, st, rs);
		}
	}
	public int addImgs(Img i) {
		String sql = "insert into img values(null,'"+i.getImgPath()+"')";
		System.out.println(sql);
		return DBManager.executeUpdate(sql);
	}
	
	
	public Img getImgById(int id) {
		Connection conn = DBManager.getConnection();
		Statement st = null;
		ResultSet rs = null;
		Img i = null;
		try {
			st = conn.createStatement();
			rs = st.executeQuery("select * from img where imgId ="+id);
			while(rs.next()) {
				int imgId = rs.getInt("imgId");
				String imgPath = rs.getString("imgPath");
				i = new Img(imgId, imgPath);
			}
			return i;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}finally {
			DBManager.closeAll(conn, st, rs);
		}
	}
	/**
	 * 修改
	 * @param i
	 * @return
	 */
	public int updateImgs(Img i) {
		String sql = "update img set imgPath='"+i.getImgPath()+"' where imgId="+i.getImgId();
		System.out.println(sql);
		return DBManager.executeUpdate(sql);
	}
	/**
	 * 批量删除
	 * @param imId
	 * @return
	 */
	public int deleteImgById(String imId) {
		return DBManager.executeUpdate("delete from img where imgId in("+imId+")");
	}
	/**
	 * 删除
	 * @param imId
	 * @return
	 */
	public int delImgById(int imId) {
		return DBManager.executeUpdate("delete from img where imgId ="+imId);
	}
	

}
